<template>
  <div class="mod-config">
  <div v-if="!addOrUpdateVisible">
     <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="请输入名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button  type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="编号"
        width="80px;">
         <template slot-scope="scope">
            {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="名称"
         width="150px;" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column
        prop="theme"
        header-align="center"
        align="center"
        label="主题"
        width="150px;" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column
        prop="content"
        align="left"
         header-align="center"
        label="模版内容" :show-overflow-tooltip="true">
        <template slot-scope="scope">
            <p v-text="scope.row.content.replace(/<.+?>/g, '').replace(/&nbsp;/ig, '').replace(/\s/ig, '')"></p>
        </template>
        
      </el-table-column>
      <el-table-column
        prop="status"
        align="center"
        label="状态"
        width="80px">
         <template slot-scope="scope">
               <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
                v-bind:title='scope.row.status == 0 ? "启用" : "禁用"'
                @change="handleSwitch(scope.row)">
              </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="detils(scope.row.id)">详情</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[5, 8, 12, 15]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>
  <div v-if="addOrUpdateVisible">
    <p >{{!dataForm.id ? '模板新增' : '模板修改'}}</p>
     <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      
      label-width="80px"
      class="el_from"
     
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="dataForm.name"
              placeholder="请输入名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主题" prop="theme">
            <el-input
              v-model="dataForm.theme"
              placeholder="请输入主题"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
          <el-form-item label="模版内容" prop="content" style="height: 450px">
            <vue-ueditor-wrap
            v-model="dataForm.content"
            :config="myConfig"
          ></vue-ueditor-wrap>
          </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="margin-left:45%">
      <el-button @click="getback()">返回</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>

  </div>
    <!-- 弹窗, 新增 / 修改 -->
    <emsgemailtemplate-detils v-if="addOrUpdateVisible1" ref="addOrUpdate1" @refreshDataList="getDataList"></emsgemailtemplate-detils>
    <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update> -->
  </div>
</template>
<script>
  import emsgemailtemplateDetils from './emsgemailtemplate-detils'
import VueUeditorWrap from "vue-ueditor-wrap";
export default {
    data () {
      return {
         myConfig: {
        // 如果需要上传功能,找后端小伙伴要服务器接口地址
        // serverUrl: this.$config.baseUrl + 'ueditor/ueditorConfig',
        serverUrl: "http://localhost:8080/wds-demo-web-api/ueditor",
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: "/static/ueditor/",
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 工具栏是否可以浮动
        autoFloatEnabled: false,
        // 关闭自动保存
        enableAutoSave: true,
       toolbars: [
            [
              'undo', //撤销
              'bold', //加粗
              'indent', //首行缩进
              'italic', //斜体
              'underline', //下划线
              'strikethrough', //删除线
              'subscript', //下标
              'fontborder', //字符边框
              'superscript', //上标
              'formatmatch', //格式刷
              'fontfamily', //字体
              'fontsize', //字号
              'justifyleft', //居左对齐
              'justifycenter', //居中对齐
              'justifyright', //居右对齐
              'justifyjustify', //两端对齐
              'insertorderedlist', //有序列表
              'insertunorderedlist', //无序列表
              'lineheight',//行间距
            ]
          ],
        'fontfamily':[
          { label:'',name:'songti',val:'宋体,SimSun'},
          { label:'仿宋',name:'fangsong',val:'仿宋,FangSong'},
          { label:'仿宋_GB2312',name:'fangsong',val:'仿宋_GB2312,FangSong'},
          { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
          { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'},
          { label:'',name:'heiti',val:'黑体, SimHei'},
          { label:'',name:'lishu',val:'隶书, SimLi'},
          { label:'',name:'andaleMono',val:'andale mono'},
          { label:'',name:'arial',val:'arial, helvetica,sans-serif'},
          { label:'',name:'arialBlack',val:'arial black,avant garde'},
          { label:'',name:'comicSansMs',val:'comic sans ms'},
          { label:'',name:'impact',val:'impact,chicago'},
          { label:'',name:'timesNewRoman',val:'times new roman'}
        ],
          // 初始容器高度
          initialFrameHeight: 350,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 上传文件接口
          enableAutoSave: false,
          elementPathEnable: false,
          wordCount: false,
        },
        dataForm: {
          key: '',
          id: 0,
        name: "",
        theme: "",
        content: "",
        status: 1,
        addUser: "",
        replaceCode: "",
        addTime: "",
        editUser: "",
        editTime: "",
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        addOrUpdateVisible1: false,
        editorOption: {},
      dataRule: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        theme: [{ required: true, message: "主题不能为空", trigger: "blur" }],
        content: [
          { required: true, message: "模版内容不能为空", trigger: "blur" },
        ],
      }
      }
    },
    components: {
      emsgemailtemplateDetils,
      VueUeditorWrap
    },
    activated () {
     this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/emsgemailtemplate/list'),
          method: 'get',
          params: this.$http.adornParams({
            'pageNumber': this.pageIndex,
            'pageSize': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.records
            this.totalPage = data.page.total
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      getback(){
        this.addOrUpdateVisible = false
        this.dataForm={}
      },
       //禁用启用
      handleSwitch(val){
         this.$confirm(`确定对[id=${val.id}]进行[${val.status==1 ? '启用' : '禁用'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
         this.$http({
          url: this.$http.adornUrl(`/emsgemailtemplate/status/${val.id}/${val.status}`),
          method: 'get',
          data: this.$http.adornParams({

          })
        }).then(({data}) => {
          if (data && data.code === 0) {
               this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
          } else {
          }
        })
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.dataForm.id = id || 0;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/emsgemailtemplate/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
               this.dataForm=data.emsgEmailTemplate
             
            }
          });
        }
      });
       
      },
      detils(id){
          this.addOrUpdateVisible1 = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate1.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/emsgemailtemplate/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 表单提交
    dataFormSubmit() {
      // /* 去除&nbsp; */
      // let content = this.dataForm.content.replace(/&nbsp;/gi, "");
      // /* 去除空格 */
      // let content1 = content.replace(/\s/gi, "");
      // let content2 = content1.replace(/<.+?>/g, "");
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/emsgemailtemplate/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              theme: this.dataForm.theme,
              content: this.dataForm.content,
              replaceCode: this.dataForm.replaceCode,
              status: this.dataForm.status,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                   this.addOrUpdateVisible = false
                  this.dataForm={}
                   this.getDataList()
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    }
  }
</script>
